package hn.cch.reactive.controller;


import com.github.benmanes.caffeine.cache.Cache;
import hn.cch.reactive.entity.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.cache.CacheFlux;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("flux")
public class FluxController {

    private static final Logger logger = LoggerFactory.getLogger(FluxController.class);

    @Autowired
    private Cache<String, Object> objectCache;

    @GetMapping("just")
    public Flux<Message> just(@RequestParam(value = "key") String key) {
        Message message = Message.success();
        message.setData(key);
        return Flux.just(message);
    }


    @GetMapping("testCacheFlux")
    public Flux<Message> testCacheFlux(@RequestParam(value = "key") String key) {
        Message message = Message.success();
        message.setData(key);
        logger.info("testCacheFlux key:{}", key);
        Flux<Message> result = CacheFlux
            .lookup(objectCache.asMap(), key, Message.class)
            .onCacheMissResume(Flux.just(message));
        return result;
    }

}
